<template>
  <div class="wb-video" ref="videoCon">
    <div ref="videoPlayer" class="video-player"></div>
  </div>
</template>

<script>
import { commonUtils } from '@/components/utils/common-utils'
import { utils } from '@/components/utils/utils'
import { EventBus } from '@/store/index'
import { mapActions, mapGetters } from 'vuex'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import {  getCompIdByParam } from '@/plugins/utils'

// x5-video-player-type="h5" x5-video-player-fullscreen='true' :preload="preload"
//currentTime 设置或返回视频中的当前播放位置（以秒计）。 duration	返回视频的长度（以秒计）。
//按钮触发视频跳转[{gapTime:0.2,popId:2},{}] 在interaction.video中记录点击的数据，在最后根据不同的数据发不同的博文
//defaultPlaybackRate 设置或返回视频的默认播放速度。
//playbackRate 设置或返回视频播放的速度。
const BTN_WIDTH = 100;
export default {
  mixins: [utils, commonUtils],
  props: {
    compItem: Object,
    isRight: Boolean,
    preload: String
  },
  setup () {
    return {
      pauseIndex: 0,
      isSeek: true,
      timeSectionList: [],
      videoPlayer_: null,//这中变量不能放在这里，这里的数据都会以代理的形式触发，会导致有些方法不会执行
      videoPlayer: null,//ref
      setInlineCb: null,
    };
  },
  created() {
    this.playBtnColor = this.item.playBtnColor;
    if (!window.DPlayer) {
      this.dynamicsLoadScript(this.env.baseUrl + "js/DPlayer.min.js", "DPlayer", this.initVideo);
    }
    if(!this.isH5Edit && this.siteInfo.md.isIPhone && !window.enableInlineVideo){
      this.dynamicsLoadScript(this.env.baseUrl + "js/iphone-inline-video.min.js", "enableInlineVideo", this.init);
    }

    this.timeSectionList = this.compItem.lists;
    _.forEach(this.timeSectionList, (item) => {
      this.hiddenOrDisplayComp(item, false);
    })

    if(this.isH5Edit){
      return
    }
    EventBus.$off("pauseVideo", this.onPause);
    EventBus.$on("pauseVideo", this.onPause);

    EventBus.$off("playVideo", this.onSeekPlayVideo);
    EventBus.$on("playVideo", this.onSeekPlayVideo);

    EventBus.$off("videoMute", this.onMute);
    EventBus.$on("videoMute", this.onMute);

    EventBus.$off("switchVideo", this.onSwitchVideo);
    EventBus.$on("switchVideo", this.onSwitchVideo);

    EventBus.$off("videoPlayAudio", this.onPlayAudio);
    EventBus.$on("videoPlayAudio", this.onPlayAudio);
    // if(this.item.isDynamic){
    //   EventBus.$off("refreshDynamicData", this.onRefreshVideoUrl);
    //   EventBus.$on("refreshDynamicData", this.onRefreshVideoUrl);
    // }
  },
  mounted() {
    this.onRefreshVideoUrl()
    this.initVideo(window.DPlayer);
    this.videoInline();
    if(this.item.isFullScreen || this.compItem.conAttr.height >= MOBILE_WID_HEI.height/MOBILE_WID_HEI.adaptiveScale){
      this.$refs.videoPlayer.style.setProperty(`--video-object-fit`, "fill");
    }else{
      this.$refs.videoPlayer.style.setProperty(`--video-object-fit`, "contain");
    }
  },
  computed: {
    ...mapGetters({
      isSwiper: "isSwiper",
    }),
  },
  methods: {
    ...mapActions({
    }),
    videoInline(){
      if(this.isH5Edit){
        return
      }
      if(this.siteInfo.md.isIPhone){
        this.setInlineCb = window.setInterval(() => {
          if(this.isSetInline){
            window.clearInterval(this.setInlineCb);
          }else{
            this.init(window.enableInlineVideo);
          }
        }, this.siteInfo.reloadTime);
      }
    },
    init(enableInlineVideo){
      if(enableInlineVideo && this.videoPlayer_){
        const videos = document.getElementsByTagName("video");
        if(videos && videos.length > 0){
          this.isSetInline = true;
          _.forEach(videos, (video) => {
            enableInlineVideo(video, {
              everywhere: true
            });
          })
        }
      }
    },
    initVideo(DPlayer) {
      if(!DPlayer || this.videoPlayer_ || !this.$refs.videoPlayer){
        return
      }
      if(this.isSwiper && !(this.pageIndex >= 0 && this.statePopId <= 0 && this.pageId == (this.pageIndex+1) || this.statePopId > 0 && this.popId == this.statePopId)){
        return
      }
      let playerElement = this.videoPlayer = this.$refs.videoPlayer;
      let player = new DPlayer({
        container: playerElement,
        autoplay: this.item.isAutoPlay,
        theme: this.item.theme ? this.item.theme : '#FADFA3',
        controls: this.item.isDisplayControls,
        loop: this.item.isLoop,
        mute: this.item.isMute,
        lang: 'zh-cn',
        screenshot: true,
        hotkey: true,
        preload: this.item.isPreload ? "auto" : "metadata",
        mutex: true,
        video: {
          url: this.item.url,
          pic: this.item.poster,
          type: 'auto',
        },
      });
      this.videoPlayer_ = player;
      //http://dplayer.js.org/zh/guide.html#api
      //play pause seek toggle on switchVideo notice switchQuality destroy speed volume video

      if(!this.isH5Edit && this.compItem.conAttr.left < MOBILE_WID_HEI.width){
        player.on('play', () => {
          let videoPlayerDom = this.videoPlayer;
          this.addClass(videoPlayerDom, "dplayer-hide-controller");
        });
        // player.on('ended', this.onEnded);
        // player.on('canplay', this.onCanplay);
        player.on('timeupdate', this.onTimeupdate);
      }
      // abort canplay canplaythrough durationchange emptied ended error loadeddata loadedmetadata loadstart mozaudioavailable pause play playing progress ratechange
      // seeked seeking stalled suspend timeupdate volumechange waiting

      // screenshot thumbnails_show thumbnails_hide danmaku_show danmaku_hide danmaku_clear danmaku_loaded danmaku_send danmaku_opacity
      // contextmenu_show contextmenu_hide notice_show notice_hide quality_start quality_end destroy resize fullscreen fullscreen_cancel webfullscreen
      // webfullscreen_cancel subtitle_show subtitle_hide subtitle_change

      this.$nextTick(() => {
        // let dplayerVideoWrap = this.videoPlayer.querySelector(".dplayer-video-wrap");
        // dplayerVideoWrap.style.backgroundImage = 'url("' + this.item.poster + '")';

        let dplayerNotice = this.videoPlayer.querySelector(".dplayer-notice");
        dplayerNotice.style.display = "none";

        let playBtn = this.videoPlayer.querySelector(".dplayer-mobile-play");
        this.playBtn = playBtn;
        // let dplayerMask = this.videoPlayer.querySelector(".dplayer-controller-mask");
        let dplayerControls = this.videoPlayer.querySelector(".dplayer-controller");

        this.refreshPlayBtnStyle();

        // dplayerMask.style.display = "none";
        if(this.item.isAutoPlay || this.item.isFullScreen){
          playBtn.style.display = "none";
          this.onPlay();
        }else{
          if(this.isH5Edit) {
            playBtn.style.display = "block";
          }
          // dplayerMask.style.display = "block";
        }

        if(this.item.isDisplayControls && !this.isH5Edit){
          dplayerControls.style.display = "block";
        }else{
          dplayerControls.style.display = "none";
        }
        this.videoInline();
        // this.removeLoading();
      })
    },
    refreshPlayBtnStyle() {
      this.$refs.videoPlayer.style.setProperty(`--video-poster`, 'url(' + this.item.poster + ')');
      this.$refs.videoPlayer.style.setProperty(`--video-play-btn-color`, this.item.playBtnColor);
      if(this.isH5Edit) {
        let btnPlay = this.videoPlayer.querySelector('.dplayer-mobile-play');
        btnPlay.style.width = BTN_WIDTH + 'px';
        btnPlay.style.height = BTN_WIDTH + 'px';
        let svg = btnPlay.querySelector('.dplayer-mobile-play svg path');
        svg.style.fill = this.item.playBtnColor;
      }
    },
    onTimeupdate(){
      if(!this.videoPlayer_) return;
      const video = this.videoPlayer_.video;
      //播放到特定时间段触发弹层
      if(this.compItem.commonAttr.isAddTimeSection){
        let item;
        for(let i = 0, len = this.timeSectionList.length; i < len; i++){
          item = this.timeSectionList[i];
          if(this.videoPlayer_.video.currentTime >= parseFloat(item.time) && i == this.pauseIndex){
            if(this.compItem.isPauseInTimeSection){
              this.onPause();
            }
            this.videoEndResult(item);
            this.pauseIndex++;
            break;
          }
        }
      }
      if(video.currentTime + 0.1 >= video.duration){
        //全屏默认是停止在 视频 时长的前0.1秒，别的情况都停止在视频开始位置
        this.onPause();
        if(!this.item.isFullScreen && this.compItem.conAttr.height < MOBILE_WID_HEI.height/MOBILE_WID_HEI.adaptiveScale) {
          this.videoPlayer_.seek(0);
          // if(this.siteAttrs.isDisplayDebuggerText){
          //   EventBus.$emit("displayDebuggerInfo", { text: "ended currentTime: " + video.currentTime });
          // }
        }
        this.onEnded();
      }
    },
    onEnded() {
      this.pauseIndex = 0;
      let resultData = null;
      if(this.compItem.commonAttr.isAddTimeSection){
        resultData = this.timeSectionList[this.timeSectionList.length-1];
      }else{
        resultData = this.item;
      }
      this.videoEndResult(resultData);
    },
    videoEndResult(resultData){
      _.forEach(this.timeSectionList, (item) => {
        this.hiddenOrDisplayComp(item, false);
      })
      if(resultData.popId > 0){
        this.showPop(resultData.popId);
      }else if(resultData.pageId > 0){
        this.showPage(resultData.pageId);
      }else if(resultData.compId && resultData.compId.length > 0){
        this.hiddenOrDisplayComp(resultData, true);
      }
    },
    hiddenOrDisplayComp(resultData, isVisible){
      let compId = getCompIdByParam(resultData.compId);
      let commonAttr = { isVisible };
      this.$store.commit('updateComponentVisible', { id: compId, commonAttr });
    },
    onPlay() {
      if((this.pageIndex >= 0 && this.statePopId <= 0 && this.pageId == (this.pageIndex+1) || this.statePopId > 0 && this.popId == this.statePopId) && this.compItem.conAttr.left < MOBILE_WID_HEI.width){
        this.videoPlayer_ && this.videoPlayer_.play();
        // this.removeLoading();
        this.sendStatics();
      }
    },
    onSeekPlayVideo(videoData) {
      if(videoData){
        if(videoData.isPlay){
          this.onPlay();
        }
        this.videoPlayer_.seek(_.toNumber(videoData.time));
      }else{
        this.onPlay();
      }
    },
    onPause() {
      this.videoPlayer_ && this.videoPlayer_.pause();
    },
    onMute() {
      this.videoPlayer_ && this.videoPlayer_.mute();
    },
    onPlayAudio(){
      this.videoPlayer_ && this.videoPlayer_.unmute();
    },
    onSwitchVideo(videoData){
      if(videoData.timeSectionList){
        this.timeSectionList = videoData.timeSectionList;
      }
      this.videoPlayer_.switchVideo({ url: videoData.url});
      this.onPlay();
    },
    sendStatics(){
      let jumpUrl = "video";
      let comType = "click";
      let wModule = "jump";
      this.onPostStatics(null, { comType, wModule, jumpUrl });
    },
    removeLoading(){
      let this_ = this;
      this.loadingCb = window.setInterval(() => {
        if(this_.$refs.videoPlayer && this_.$refs.videoPlayer.classList.contains("dplayer-loading")){
          this_.removeClass(this_.$refs.videoPlayer, "dplayer-loading");
          window.clearInterval(this_.loadingCb);
        }
      }, this.siteInfo.reloadTime)
    },
    destroyVideo() {
      if(this.videoPlayer_){
        this.videoPlayer_.pause();
        this.videoPlayer_.destroy();
        this.videoPlayer_.on('timeupdate', null);
        this.videoPlayer_ = null;
        this.isSetInline = false;
        // const videos = document.getElementsByClassName("wb-video");
        // _.forEach(videos, (video) => {
        //   video.innerHTML = '';
        // })
      }
    },
    onRefreshCommonAttr() {
      if(this.playBtnColor != this.item.playBtnColor){
        this.refreshPlayBtnStyle();
      }
    },
    onRefreshVideoUrl(){
      if(this.isH5Edit){
        return
      }
      // 抽奖修改视频地址
      if(this.item.isDynamic && this.shareData.url || this.shareData.videoUrl) {
        let url;
        let posterUrl;
        if(this.shareData.videoUrl) {
          url = this.shareData.videoUrl;
          posterUrl = this.shareData.posterUrl;
        } else {
          let urls = this.shareData.url.split(',');
          url = urls[0];
          posterUrl =urls[1] ?urls[1] : '';
        }
        if(this.videoPlayer_) {
          this.videoPlayer_.switchVideo({
            url: url,
            pic: posterUrl,
          })
        }else{
          this.item.url = url
          this.item.poster = posterUrl
        }
      }
    },
  },
  watch: {
    pageIndex() {
      if(this.isSwiper){
        if(this.pageIndex >= 0 && this.pageId == (this.pageIndex+1) || this.statePopId > 0 && this.popId == this.statePopId){
          this.$nextTick(() => {
            this.initVideo(window.DPlayer);
            this.videoInline();
          })
        }else{
          this.destroyVideo();
        }
      }
    }
  },
  beforeUnmount() {
    if(this.isH5Edit) {
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
      return
    }
    // if(this.item.isDynamic){
    //   EventBus.$off("refreshDynamicData", this.onRefreshVideoUrl)
    // }
    EventBus.$off("pauseVideo", this.onPause);
    EventBus.$off("playVideo", this.onSeekPlayVideo);
    EventBus.$off("videoMute", this.onMute);
    EventBus.$off("switchVideo", this.onSwitchVideo);

    EventBus.$off("videoPlayAudio", this.onPlayAudio);
    this.destroyVideo()
  },
};
</script>
<style lang="scss">
  .wb-video, .video-player{
  --video-object-fit: contain;
  --video-play-btn-color: '#fff';
  --video-poster: url();

  width: inherit;
  height: inherit;
}
.dplayer-video-wrap{
  background-repeat: no-repeat;
  background-color: transparent;
  background-image: var(--video-poster);
  background-size: var(--video-object-fit);
}
video {
  width: 100%;
  height: 100%;
  object-fit: var(--video-object-fit);
}
.dplayer.dplayer-loading .dplayer-bezel .diplayer-loading-icon {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting{
  display: none;
}
.dplayer-mobile-play {
  width: var(--size-100);
  height: var(--size-100);
}
.dplayer svg path {
  fill: var(--video-play-btn-color);
}
</style>
